package com.qigao.mall.web.utils;

import com.qigao.mall.commons.dto.PicDto;
import com.qigao.mall.commons.enums.IdTypeEnum;
import com.qigao.mall.commons.utils.DateUtil;
import com.qigao.mall.commons.utils.FileUtils;
import com.qigao.mall.commons.utils.IDUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author luiz
 * @Title: MultiFileUtils
 * @ProjectName tokyo
 * @Description: TODO
 * @date 2019-04-09 14:05
 */
public class MultiFileUtils {
    public static PicDto saveFile(MultipartFile multipartFile, String fileSavePath, String userNo) {
        try {
        PicDto picDto=new PicDto();
        int  fileSize= 0;
        fileSize = multipartFile.getBytes().length;
        String origFileName=multipartFile.getOriginalFilename();
        String fileType=origFileName.split("\\.")[1];
        byte[] fileByte=multipartFile.getBytes();
        String fileNo= IDUtils.genIdStr(IdTypeEnum.PIC.getCode());
        String newFileName=fileNo+"."+fileType;
        String filePath=fileSavePath+"/"+ DateUtil.getNowDateStr()+"/";
        FileUtils.uploadFile(fileByte,filePath,newFileName);
        String zipPicFileNo=IDUtils.genIdStr(IdTypeEnum.PIC.getCode());
        String fromPicPath=filePath+newFileName;
        String zipPicPath=filePath+zipPicFileNo+"."+fileType;
        //图片压缩
        FileUtils.zipImage(fromPicPath,zipPicPath);
        String narrowPicFileNo=IDUtils.genIdStr(IdTypeEnum.PIC.getCode());
        String narrowPicPath=filePath+narrowPicFileNo+"."+fileType;
        //图片缩放
        FileUtils.narrowImage(fromPicPath,narrowPicPath);
        picDto.setFileNo(fileNo);
        picDto.setNarrowFileNo(narrowPicFileNo);
        picDto.setZipFileNo(zipPicFileNo);
        picDto.setUserNo(userNo);
        picDto.setFileName(newFileName);
        picDto.setOrigFileName(origFileName);
        picDto.setFileSize(fileSize);
        picDto.setFileType(fileType);
        picDto.setPicPath(filePath);
        return picDto;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
